<?php

namespace app\user\controller\user;

use app\admin\logic\ExportQuestionLogic;
use app\admin\logic\ImportQuestionLogic;
use app\admin\service\QuestionForm;
use app\common\controller\Userend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

/**
 * 课程关联的题库
 *
 * @icon fa fa-circle-o
 */
class Question extends Userend
{

    /**
     * Question模型对象
     * @var \app\admin\model\Question
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'question_name';

    protected $dataLimit = true;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Question;
    }

    /**
     * 列表
     * @return string|Json
     * @throws Exception
     * @throws DbException
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 查询用户课程
        $userInfo = $this->auth->getUserinfo();

        $courseModel = new \app\common\model\Course();
        $courseList = $courseModel->where(['user_id' => $userInfo['user_id']])->select();
        $allCourseId = array_column((array)$courseList, 'id');

        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $course_id = $param['course_id'] ?? 0;

        // 提交查询
        if ($this->request->isAjax()) {
            // 如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $otherWhere = [];
            if ($course_id) {
                $otherWhere['course_id'] = $course_id;
            }
            $userCourseWhere = [];
            if ($allCourseId) {
                $userCourseWhere['course_id'] = ['in', $allCourseId];
            } else {
                $userCourseWhere['course_id'] = ['in', -1];
            }
            $list = $this->model
                ->with('course')
                ->where($where)
                ->where($otherWhere)
                ->where($userCourseWhere)
                ->order($sort, $order)
                ->paginate($limit);
            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        $this->view->assign('course_id', $course_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     */
    public function add()
    {
        // 请求参数
        $param = $this->request->param();
        $course_id = $param['course_id'] ?? 0;
        $userInfo = $this->auth->getUserinfo();
        $uid = $userInfo['user_id'] ?? 0;
        if (empty($uid)) {
            $this->error('获取用户身份失败');
        }

        // 提交保存
        if ($this->request->isPost()) {
            // 提取参数
            $paramRow = $param['row'] ?? [];
            if (!$paramRow) {
                $this->error('请求参数不得为空');
            }

            // 检查参数
            $question_type = $paramRow['question_type'] ?? 0;
            if (empty($paramRow['question_type'])) {
                $this->error('题目类型不能为空');
            }
            if (empty($paramRow['questionAsk'])) {
                $this->error('题目标题不能为空');
            }
            if (empty($paramRow['correctOption'])) {
                $this->error('题目答案不能为空');
            }
            if (empty($paramRow['course_id'])) {
                $this->error('请选择课程');
            }
            if (empty($paramRow['paper_id'])) {
                $this->error('请选择试卷');
            }

            // 题目数据
            $newQuestionData = [];
            $newQuestionData['questionAsk'] = $paramRow['questionAsk'];   // 题目标题

            // 题目答案
            $newQuestionData['correctOption'] = $paramRow['correctOption'];  // 题目答案
            if (is_array($paramRow['correctOption'])) {
                $newQuestionData['correctOption'] = join('', $paramRow['correctOption']);
            }

            // 题目选项
            $selectOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
            foreach ($selectOptions as $option) {
                if (array_key_exists($option, $paramRow) && $paramRow[$option] != '') {
                    $newQuestionData['answerOption'][$option] = $paramRow[$option];
                }
            }

            // 题目解析
            if (isset($paramRow['explanation']) && $paramRow['explanation']) {
                $newQuestionData['explanation'] = $paramRow['explanation'];
            }

            // 更新题目数据
            $time = time();
            $saveData = [
                'type' => 4,
                'question_type' => $question_type,
                'extend_id' => $paramRow['paper_id'],
                'course_id' => $paramRow['course_id'],
                'question_name' => $newQuestionData['questionAsk'],
                'question_hash' => $this->model->buildHash($newQuestionData),
                'question_data' => json_encode($newQuestionData),
                'uid' => $uid,
                'a_time' => $time,
                'u_time' => $time,
            ];
            $isUpdate = $this->model->insert($saveData);
            if ($isUpdate === false) {
                $this->error('更新数据失败');
            }
            $this->success();
        }

        $this->view->assign('course_id', $course_id);
        return parent::add();
    }

    /**
     *  编辑
     * @param null $ids
     * @return string
     * @throws DbException
     * @throws Exception
     */
    public function edit($ids = null): string
    {
        // 获取用户身份
        $userInfo = $this->auth->getUserinfo();
        $uid = $userInfo['user_id'] ?? 0;
        if (empty($uid)) {
            $this->error('获取用户身份失败');
        }

        // 查询详情
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['uid'] != $uid) {
            $this->error(__('您无权限编辑此题目'));
        }
        $row = $row ? $row->toArray() : [];

        // 原始题目数据
        $oldQuestionData = json_decode($row['question_data'], true);
        if (!$oldQuestionData) {
            $this->error('解析原始题目数据失败');
        }

        // 提交保存
        $param = $this->request->param();
        if ($this->request->isPost()) {
            // 提取参数
            $paramRow = $param['row'] ?? [];
            if (!$paramRow) {
                $this->error('请求参数不得为空');
            }
            if (empty($paramRow['question_type'])) {
                $this->error('题目类型不能为空');
            }
            if (empty($paramRow['questionAsk'])) {
                $this->error('题目标题不能为空');
            }
            if (empty($paramRow['correctOption'])) {
                $this->error('题目答案不能为空');
            }

            // 题目数据
            $newQuestionData = [];
            $newQuestionData['questionAsk'] = $paramRow['questionAsk'];   // 题目标题

            // 题目答案
            $newQuestionData['correctOption'] = $paramRow['correctOption'];  // 题目答案
            if (is_array($paramRow['correctOption'])) {
                $newQuestionData['correctOption'] = join('', $paramRow['correctOption']);
            }

            // 题目选项
            $selectOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
            foreach ($selectOptions as $option) {
                if (array_key_exists($option, $paramRow) && $paramRow[$option] != '') {
                    $newQuestionData['answerOption'][$option] = $paramRow[$option];
                }
            }

            // 题目解析
            if (isset($paramRow['explanation']) && $paramRow['explanation']) {
                $newQuestionData['explanation'] = $paramRow['explanation'];
            }


            // 更新题目数据
            $time = time();
            $saveData = [
                'question_type' => $paramRow['question_type'],
                'question_name' => $newQuestionData['questionAsk'],
                'question_hash' => $this->model->buildHash($newQuestionData),
                'question_data' => json_encode($newQuestionData),
                'u_time' => $time,
                'uid' => $uid,
            ];
            $isUpdate = $this->model->where(['id' => $ids])->update($saveData);
            if ($isUpdate === false) {
                $this->error('更新数据失败');
            }
            $this->success();
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 生成Html
     * @return void
     * @throws
     */
    public function buildhtml()
    {
        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $action = $param['action'] ?? 0;

        // 检查数据
        if (!$action) {
            $this->error('请选择生成方式');
        }
        $questionType = $param['question_type'] ?? 0;
        $questionData = null;
        if ($action == 1) {
            $action = $param['action'] ?? 0;
            $questionType = $questionType ?: 1;
            if (!$questionType) {
                $this->error('请选择题目类型');
            }
        }
        if ($action == 2) {
            $id = $param['id'] ?? 0;
            if (!$id) {
                $this->error('数据id不得为空');
            }
            $row = $this->model->find($id);
            if (!$row) {
                $this->error('数据不存在');
            }
            if (!$questionType) {
                $questionType = $row['question_type'];
            }
            $questionData = json_decode($row['question_data'], true);
            if (!$questionData) {
                $this->error('题目数据解析失败');
            }
        }

        // 生成Html
        $questionForm = new QuestionForm($action, $questionType, $questionData);
        $html = $questionForm->build();
        $this->success("", "", $html);
    }

    /**
     * 导入题目
     */
    public function importQuestion()
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导入课程不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导入试卷不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            try {
                Db::startTrans();
                (new ImportQuestionLogic())->import($params['course_id'], $params['paper_id'], $params['attachment']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        return $this->view->fetch();
    }

    /**
     * 导出题目
     * @return string
     * @throws \think\Exception
     */
    public function exportQuestion()
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导出课程不得为空'));
            }
            try {
                $filePath = (new ExportQuestionLogic())->export([$params['course_id']], [$params['paper_id'] ?? 0]);
            } catch (\Exception $exception) {
                $this->error(__($exception->getMessage()));
            }
            $this->success('导出成功', null, $filePath);
        }
        return $this->view->fetch();
    }

    /**
     * 清空题目
     * @return string
     * @throws \think\Exception
     */
    public function clearQuestion()
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('请选择需要清空题目的课程'));
            }
            // 清空题目
            $where = ['type' => 4, 'course_id' => $params['course_id']];
            if (!empty($params['paper_id'])) {
                $where['paper_id'] = $params['paper_id'];
            }
            $model = new \app\admin\model\Question();
            $model->where($where)->delete();
            $this->success('清空成功');
        }
        return $this->view->fetch();
    }

    /**
     * 题目查重
     * @return string
     */
    public function repeatQuestion($ids = null)
    {
        // 请求参数
        $param = $this->request->param();

        // 提交保存
        if ($this->request->isPost()) {
            // 提取参数
            $paramRow = $param['row'] ?? [];
            $course_id = $paramRow['course_id'] ?? 0;

            // 检查参数
            if (empty($course_id)) {
                $this->error('请选择课程');
            }

            // 查询重复题目
            $where = [
                'course_id' => intval($course_id)
            ];
            $repeatList = $this->model->where($where)->group('question_name')->having('count(question_name)>1')->column('question_name');
            if (!$repeatList) {
                $this->error('未查询到重复题目');
            }

            // 查询全部题目编号
            $where['question_name'] = ['in', $repeatList];
            $repeatList = $this->model->where($where)->column('id');
            if (!$repeatList) {
                $this->error('未查询到重复题目');
            }
            $this->success('', null, join(',', $repeatList));
        }
        $this->view->assign('ids', $ids);
        return parent::add();
    }

}
